﻿using System;
using System.Collections.Generic;

namespace Ex04.Menus.Delegates
{
    public class MainMenu
    {
        private const bool k_BaseMenu = true;

        private MenuItem m_BaseMenu;
        private Stack<MenuItem> m_MenuContext = new Stack<MenuItem>();

        public MainMenu(string i_MainMenuTitle)
        {
            m_BaseMenu = new MenuItem(i_MainMenuTitle);
            m_BaseMenu.IsBaseMenuItem = k_BaseMenu;
            m_MenuContext.Push(m_BaseMenu);
        }

        /// <summary>
        /// Will add a menu item
        /// </summary>
        /// <param name="i_MenuItemToAdd">
        ///     The menu item to add to the main menu
        ///     <remarks>
        ///         Must not be null, in such case will throw ArgumentNullException
        ///     </remarks>
        /// </param>
        public void AddMenuItem(MenuItem i_MenuItemToAdd)
        {
            if (i_MenuItemToAdd == null)
            {
                throw new ArgumentNullException("null menu item can not be added");
            }

            m_BaseMenu.AddMenuItem(i_MenuItemToAdd);
        }

        /// <summary>
        /// This is the main function of the main menu
        /// Will show the menu 
        /// </summary>
        public void Show()
        {
            const bool v_Done = true;
            int optionChosen;
            bool isDoneWithMenu;

            do
            {
                m_MenuContext.Peek().Execute();
                MenuItem currentMenuItemContext = m_MenuContext.Peek();
                if (currentMenuItemContext.IsSubMenu())
                {
                    optionChosen = currentMenuItemContext.OptionChosen;
                    if (optionChosen != MenuItem.BackOrExitIndex)
                    {
                        m_MenuContext.Push(currentMenuItemContext.MenuItems[optionChosen - 1]);
                    }
                    else
                    {
                        m_MenuContext.Pop();
                    }

                    isDoneWithMenu = (optionChosen == MenuItem.BackOrExitIndex) && (m_MenuContext.Count == 0);
                }
                else
                {
                    m_MenuContext.Pop();
                    isDoneWithMenu = !v_Done;
                    Console.WriteLine("Press any key to continue....");
                    Console.ReadKey();
                }
                
            } while (!isDoneWithMenu);

            Console.WriteLine("Press any key to exit....");
            Console.ReadKey();
        }
    }
}
